import os
import re
from importlib import import_module
from playwright.sync_api import sync_playwright

import time
from pathlib import Path
import sys
import subprocess

path = os.path
CURRENT_FILE_PATH = Path(__file__).resolve()
ROOT_PATH = CURRENT_FILE_PATH.parent
CORE_PATH = ROOT_PATH / "core"
LIBS_PATH = ROOT_PATH / "common/libs"
PUBLIC_MODULE_PATH = ROOT_PATH / "common/public_module"
SUB_PROCESS_PATH = ROOT_PATH / "sub_process"
print(LIBS_PATH)
for path in [CORE_PATH, LIBS_PATH, PUBLIC_MODULE_PATH, SUB_PROCESS_PATH]:
    if path.is_dir() and str(path) not in sys.path:
        sys.path.append(str(path))

printer = import_module("printer").IndentPrinter()

CONFIG = import_module("config")
SUB_PROCESS = CONFIG.SUB_PROCESS

os.environ["COMMON_PATH"] = str(ROOT_PATH / "common")
os.environ["DATA_PATH"] = str(CONFIG.DATA_PATH)

sso = import_module("sso_auth")
sn = import_module("switch_network")
printer = import_module("printer").IndentPrinter(indent=1)
auth_info = None
data_path = os.environ["DATA_PATH"]
base_headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
}


browser_port = "9222"
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
edge_path = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"


def launch_chrome():
    process = subprocess.Popen([edge_path, f"--remote-debugging-port={browser_port}"])
    return process



def main():
    global auth_info

    # sn.connect_to_internal()
    if sn.wait_for_system("10.243.24.152", "8080"):
        print("家集客系统已可用")
        printer("[下载数据] 开始")
        printer.add(1)

        with sync_playwright() as p:
            browser = p.chromium.connect_over_cdp(f"http://localhost:{browser_port}")
            default_context = browser.contexts[0]
            page = default_context.pages[0]

            page.goto(
                "http://10.243.24.152:8080/fgios-ui/report-management/bi/list",
                timeout=600000,
            )

            page.wait_for_selector(".sub-system-name")

            page.wait_for_selector(".el-select.select-with-bg.el-select--small")
            page.click(".el-tag__close.el-icon-close")
            name_list = [
                "放装终端未纳管",
                "可用设备长期滞留",
                "该翻新报废设备长期未处理",
                "非已使用串码在RMS纳管",
                "已使用设备无有效放装单号",
                "电视账号未激活或激活后长期未使用",
            ]
            for name in name_list:
                page.locator("input[placeholder='报表名称']").clear()
                page.type("input[placeholder='报表名称']", name)
                page.click("button:has-text('查询')")

                if name == "放装终端未纳管":
                    page.get_by_title(f"{name}", exact=True).click()
                else:
                    page.get_by_title(f"终端自查_{name}").click()

                page.wait_for_selector("[title=iframe]")
                frame_element = page.query_selector("[title=iframe]")

                if frame_element:
                    frame = frame_element.content_frame()

                    frame.wait_for_selector(
                        ".m-ListFilter:has-text('202')", timeout=60000
                    )
                    printer(f"进入iframe[{name}]")
                    frame.click(".m-ListFilter:has-text('day_id')")
                    printer("开始选择日期")
                    frame.wait_for_selector(".m-graphic-filter-dropdown")
                    frame.hover(".m-graphic-filter-dropdown")

                    li_count = frame.locator("li[title]").count()
                    latest_text = (
                        frame.locator("li[title]")
                        .nth(li_count - 1)
                        .get_attribute("title")
                    )
                    printer(f"当前最新日期：{latest_text}")
                    cur_day_id = frame.locator(".ttlLabel").nth(0).text_content()
                    if cur_day_id and cur_day_id.find(latest_text) < 0:
                        frame.click(selector="span.clear", force=True)
                        frame.click(f"li[title='{latest_text}']")
                        frame.click(
                            selector=".m-graphic-filter-dropdown .bar .action .u-btn-primary",
                            force=True,
                        )
                    frame.click(".m-window-mask")
                    time.sleep(3)

                    printer("开始选择地区")
                    frame.locator(".m-ListFilter:has-text('region')").click()
                    frame.wait_for_selector(".m-graphic-filter-dropdown")
                    frame.hover(".m-graphic-filter-dropdown")

                    cur_region = (
                        frame.locator(".ttlLabel")
                        .nth(1)
                        .text_content()
                        .replace("\n", "", -1)
                        .replace(" ", "", -1)
                    )
                    if cur_region and cur_region.find("茂名") < 0:
                        frame.click(selector="span.clear", force=True)

                        frame.click(f"li[title='茂名']")
                        frame.click(
                            selector=".m-graphic-filter-dropdown .bar .action .u-btn-primary",
                            force=True,
                        )

                    printer(
                        "当前地区：",
                        re.sub(
                            r"region:|\s",
                            "",
                            frame.locator(
                                ".m-ListFilter:has-text('region')"
                            ).text_content(),
                        ).strip(),
                    )
                    frame.click(".m-window-mask")
                    # frame.hover(".m-dashbox-table")  # 鼠标悬浮在表格上
                    # frame.click(".opts:nth-child(2)")  # 点击三个点的图标按钮
                    # frame.wait_for_selector(".context-menu-new")  # 等待更多菜单弹出
                    # frame.hover(".menu-item-ctn.haschild")
                    # frame.get_by_text("导出Excel").click()
                    # frame.get_by_text("普通导出").click()
                    # frame.get_by_text("确定").click()
                    time.sleep(3)
                    printer(f"开始下载[{name}]")
                    frame.get_by_text("导出").click()  # 顶部导出按钮
                    
                    frame.wait_for_selector(".context-menu-new")
                    frame.evaluate(
                        """
                      () => {
                        console.log("来自 playwright")
                        document.querySelector('.menu-item-ctn.haschild:nth-child(1)>.menu-items').style='display:block';
                      }
                      """
                    )
                    frame.get_by_text("导出Excel").first.click()
                    frame.get_by_text("导出全部图表").click()
                    # Start waiting for the download
                    with page.expect_download(timeout=60000) as download_info:
                        # Perform the action that initiates download
                        frame.get_by_text("确定").click()
                    download = download_info.value

                    download.save_as(
                        os.path.join(data_path, f"{name}.xlsx")
                    )

                    printer(f"[{name}]导出数据成功,返回上级")
                    page.get_by_text("返 回").click()
            input("Press Enter to close the browser...")

        printer("[下载数据] 👏 完成，总耗时<run_time>。", run_time="hh:mm:ss")

        # sn.connect_to_internet()


if __name__ == "__main__":
    main()
